package linuxbox.calendar.bean;

import java.util.*;

import linuxbox.exception.*;
import linuxbox.util.*;

import linuxbox.calendar.logic.BoxCalendarEntry;

public class BoxCalendarEntryBean extends BoxCalendarEntry {
	protected DbAdapter m_db = null;
	protected boolean m_bTransaction = false;
	static protected String m_TableName = "box_calendar";

	public BoxCalendarEntryBean(BoxCalendarEntryKey pk, DbAdapter db) {
		this.init(pk, db);
	}

	public BoxCalendarEntryBean(BoxCalendarEntryKey pk) {
		this.init(pk, null);
	}

	public void init(BoxCalendarEntryKey pk, DbAdapter db) {
		if (db != null) {
			m_db = db;
			m_bTransaction = true;
		}
		if (pk != null) {
			setID(pk.getID());
			setUserID(pk.getUserID());
		}
	}

	public String getTableName() {
		return m_TableName;
	}

	public void setTableName(String str) {
		m_TableName = str;
	}

	public void makeConnection() throws Exception {
		if (m_db == null)
			m_db = new DbAdapter(true);
	}

	public void closeConnection() throws Exception {
		if (m_db != null) {
			m_db.close();
			m_db = null;
		}
	}

	public void load() throws Exception {
		StringBuffer sql = new StringBuffer();

		sql.append("select id, userid, createdby, subject, " +
						"description, fromtime, totime, category, " +
						"sharing, repeatflag, isallday from ");
		sql.append(getTableName());
		sql.append(" where id=" + getID() + " and userid=" + m_UserID);

		makeConnection();
		m_db.executeQuery(sql.toString());
		if (m_db.next()) {
			m_iID = m_db.getInt("id");
			m_CreatedBy = m_db.getInt("createdby");
			m_sSubject = m_db.getString("subject");
			m_sDescription = m_db.getString("description");
			m_FromTime = m_db.getTimestamp("fromtime");
			m_ToTime = m_db.getTimestamp("totime");
			m_sCategory = m_db.getString("category");
			m_iSharing = m_db.getInt("sharing");
			m_bRepeat = (m_db.getInt("repeatflag") != 0);
			m_bIsAllDay = (m_db.getInt("isallday") != 0);
		} else {
			if (!m_bTransaction)
				closeConnection();
			throw new LinuxboxException(ExceptionHelper.CALENDAR, "LOAD",
					"Load error:  m_iID=" + m_iID + " userid=" + m_UserID);
		}
		if (!m_bTransaction)
			closeConnection();
	}

	public void store() throws Exception {
		StringBuffer sql = new StringBuffer();
		sql.append("UPDATE ");
		sql.append(getTableName());
		sql.append(" set ");
		DBUtil.setString(sql, "category", m_sCategory, true);
		DBUtil.setInteger(sql, "sharing", m_iSharing, false);
		DBUtil.setInteger(sql, "repeatflag", ((m_bRepeat) ? 1 : 0), false);
		DBUtil.setInteger(sql, "isallday", ((m_bIsAllDay) ? 1 : 0), false);
		DBUtil.setInteger(sql, "createdby", m_CreatedBy, false);
		DBUtil.setString(sql, "subject", m_sSubject, false);
		DBUtil.setString(sql, "description", m_sDescription, false);
		DBUtil.setTimestamp(sql, "fromtime", m_FromTime, false);
		DBUtil.setTimestamp(sql, "totime", m_ToTime, false);

		sql.append(" where id=" + m_iID + " and userid=" + m_UserID);

		makeConnection();
		m_db.executeUpdate(sql.toString());
		if (!m_bTransaction)
			closeConnection();
	}

	public void refresh() throws Exception {
		load();
	}

	public void create() throws Exception {
		if (m_iID != 0) {
			String sql = "INSERT INTO ";
			sql += getTableName();
			sql += " (id,userid) VALUES(" + m_iID + "," + m_UserID + ")";
			makeConnection();
			m_db.executeUpdate(sql);
		} else {
			String sql = "select max(id) from ";
			sql += getTableName();
			makeConnection();
			m_db.executeQuery(sql);
			int max_id = 0;
			if (m_db.next()) {
				max_id = m_db.getInt(1);
			}
			max_id++;
			m_iID = max_id;
			sql = "insert into ";
			sql += getTableName();
			sql += " (id,userid) VALUES(" + max_id + "," + m_UserID + ")";
			m_db.executeUpdate(sql);
		}

		if (!m_bTransaction)
			closeConnection();
	}

	public void remove() throws Exception {
		StringBuffer sql = new StringBuffer();
		sql.append("DELETE FROM ");
		sql.append(getTableName());
		sql.append(" where id = ");
		sql.append(m_iID);
		sql.append(" and userid=");
		sql.append(m_UserID);

		makeConnection();
		m_db.executeUpdate(sql.toString());
		if (!m_bTransaction)
			closeConnection();
	}

	public int getInvitedUserCount() throws Exception {
		int count = 0;
		try {
			StringBuffer sql = new StringBuffer();
			sql.append("select count(userid) from ");
			sql.append(getTableName());
			sql.append(" where id=" + m_iID);

			makeConnection();
			m_db.executeQuery(sql.toString());
			if (m_db.next())
				count = m_db.getInt(1);
			if (!m_bTransaction)
				closeConnection();
		} catch (Exception e) {
			if (!m_bTransaction)
				closeConnection();
			throw new LinuxboxException(ExceptionHelper.CALENDAR,
					"getInvitedUserCount", "Can't find record: "
							+ e.getMessage());
		}
		return count - 1; // The query will include itself
	}

	public int[] getInvitedUsers() throws Exception {
		ArrayList users = null;
		try {
			StringBuffer sql = new StringBuffer();
			sql.append("select userid from ");
			sql.append(getTableName());
			sql.append(" where id=" + m_iID);

			makeConnection();
			m_db.executeQuery(sql.toString());
			users = new ArrayList();
			while (m_db.next()) {
				int user = m_db.getInt(1);
				if (user != m_UserID)
					users.add(new Integer(user));
			}
			if (!m_bTransaction)
				closeConnection();
		} catch (Exception e) {
			if (!m_bTransaction)
				closeConnection();
			throw new LinuxboxException(ExceptionHelper.CALENDAR,
					"getInvitedUserCount", "Can't find record: "
							+ e.getMessage());
		}
		if (users != null) {
			int[] ret = new int[users.size()];
			for (int i = 0; i < users.size(); i++)
				ret[i] = ((Integer) users.get(i)).intValue();

			return ret;
		}
		return null;
	}

	public Object findByKey() throws Exception {
		StringBuffer sql = new StringBuffer();
		sql.append("select id,userid from ");
		sql.append(getTableName());
		sql.append(" where id = ");
		sql.append(m_iID);
		sql.append(" and userid=");
		sql.append(m_UserID);
		makeConnection();
		m_db.executeQuery(sql.toString());
		BoxCalendarEntryKey pk = null;
		if (m_db.next()) {
			pk = new BoxCalendarEntryKey(m_db.getInt(1), m_db.getInt(2));
		}
		if (!m_bTransaction)
			closeConnection();
		return pk;
	}

	public Iterator findBySql(String sqlWhere) throws Exception {
		Vector v = null;
		try {
			String sql = "select id,userid from ";
			sql += getTableName();
			sql += sqlWhere;
			makeConnection();
			m_db.executeQuery(sql);
			BoxCalendarEntryKey pk = null;
			v = new Vector();
			while (m_db.next()) {
				pk = new BoxCalendarEntryKey(m_db.getInt(1), m_db.getInt(2));
				v.addElement(pk);
			}
			if (!m_bTransaction)
				closeConnection();
		} catch (Exception e) {
			if (!m_bTransaction)
				closeConnection();
			throw new LinuxboxException(ExceptionHelper.CALENDAR, "FIND",
					"Can't find record: " + e.getMessage());
		}
		return v.iterator();
	}

	public boolean updateBySql(String sql) throws Exception {
		try {
			makeConnection();
			m_db.executeUpdate(sql);
			if (!m_bTransaction)
				closeConnection();
		} catch (Exception e) {
			if (!m_bTransaction)
				closeConnection();
			throw new LinuxboxException(ExceptionHelper.CALENDAR,
					"updateBySql", "Can't update: " + e.getMessage());
		}
		return true;
	}
}
